﻿using System;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;
using System.Collections.Generic;
using System.Linq;
using PSE.Framework.UI.Resources;

namespace Sinacor.Infra.UI.Controls.SmartClient
{
    public class SinacorReportParameterWindow : SinacorWindow
    {
        #region Fields

        private List<SinacorReportFormatObjects> _formatObjects;
        private Dictionary<String, String> _subReportsTitles;
        private StackPanel _container;
        private Boolean _isManualReport;
        private string _reportTitleResourceKey;
        #endregion

        #region Properties
        public List<SinacorReportFormatObjects> FormatObjects
        {
            get { return _formatObjects; }
        }


        public static readonly DependencyProperty ColumnMappedCheckedProperty = DependencyProperty.Register("ColumnMappedChecked", typeof(Boolean), typeof(SinacorReportParameterWindow), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        public Boolean ColumnMappedChecked
        {
            get { return (Boolean)GetValue(ColumnMappedCheckedProperty); }
            set { SetValue(ColumnMappedCheckedProperty, value); }
        }

        #endregion

        #region Properties

        private Boolean _canceled = true;
        public Boolean Canceled
        {
            get
            {
                return _canceled;
            }
        }

        #endregion

        #region Constructor
        private SinacorReportParameterWindow()
        {
        }

        private SinacorReportParameterWindow(string reportTitleResourceKey)
        {
            base.AutoSaveLayoutEnabled = false;

            this.SetResourceReference(StyleProperty, "ControlReportParameterWindow");

            this._reportTitleResourceKey = reportTitleResourceKey;
            this.SetResourceReference(Window.TitleProperty, reportTitleResourceKey);

            this.CommandBindings.Add(new CommandBinding(SinacorWindowCommands.Close, btnClose_Click));
            this.CommandBindings.Add(new CommandBinding(SinacorReportCommands.Ok, btnOk_Click));
            this.CommandBindings.Add(new CommandBinding(SinacorReportCommands.Cancel, btnCancel_Click));

            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

            this.Initialized += new EventHandler(SinacorReportParameterWindow_Initialized);
        }

        void SinacorReportParameterWindow_Initialized(object sender, EventArgs e)
        {
            SinacorWindow ownerWindow = this.Owner as SinacorWindow;
            if (ownerWindow == null)
                throw new Exception("The Owner of the Window must be informed.");

            this.ModuleId = ownerWindow.ModuleId;
            this.ModulePlus = ownerWindow.ModulePlus;
            this.SetMenuHeader(ownerWindow.MenuHeader, this._reportTitleResourceKey);
        }

        /// <summary>
        /// Criar uma nova SinacorReportParameterWindow
        /// </summary>
        /// <param name="formatObjects">Objetos de formatação</param>
        /// <param name="isManualReport">Indica que se trata de um relatório manual</param>
        public SinacorReportParameterWindow(List<SinacorReportFormatObjects> formatObjects, Boolean isManualReport, string reportTitleResourceKey)
            : this(reportTitleResourceKey)
        {
            this._formatObjects = formatObjects;
            this._isManualReport = isManualReport;

        }
        /// <summary>
        /// Criar uma nova SinacorReportParameterWindow
        /// </summary>
        /// <param name="formatObjects">Objecto de formatação</param>
        /// <param name="subReportsTitles">Títulos do sub-relatórios</param>
        public SinacorReportParameterWindow(List<SinacorReportFormatObjects> formatObjects, Dictionary<String, String> subReportsTitles, string reportTitleResourceKey)
            : this(formatObjects, true, reportTitleResourceKey)
        {
            this._subReportsTitles = subReportsTitles;
        }

        #endregion

        #region Private Methods

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this._canceled = true;
            this.Close();
        }

        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            this._canceled = false;

            Int32 count = this._container.Children.Count;
            for (int i = 0; i < count; i++)
            {
                if (this._container.Children[i] is CheckBox)
                {
                    CheckBox checkBox = (CheckBox)this._container.Children[i];
                    if (!checkBox.IsChecked.Value)
                        this._formatObjects[i].IsVisible = false;
                    else
                        this._formatObjects[i].IsVisible = true;
                }
            }

            if (this._formatObjects.Count(x => x.IsVisible) == 0)
            {
                string message = (string)ResourceProviderManager.GetResourceProvider().TryGetResource("Infra.Controls.Message.ObrigatorioSelecionarColuna");
                SinacorMessageBox.Show(message, SinacorMessageBoxImage.Exclamation);
                return;
            }

            this.Close();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this._canceled = true;
            this.Close();
        }

        #endregion

        #region Public Methods

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            DockPanel header = this.GetTemplateChild("LayoutRoot") as DockPanel;
            header.MouseLeftButtonDown += new MouseButtonEventHandler(header_MouseLeftButtonDown);

            SinacorCheckBox ColumnMapped = this.GetTemplateChild("ChkColumnMapped") as SinacorCheckBox;

            if (this._isManualReport)
                ColumnMapped.Visibility = Visibility.Hidden;
            else
                ColumnMapped.Visibility = Visibility.Visible;

            this._container = this.GetTemplateChild("SinacorReportParameterContainer") as StackPanel;

            Int32 i = 1;
            foreach (SinacorReportFormatObjects item in this._formatObjects)
            {
                if (item.DisplayParameter && !String.IsNullOrEmpty(item.TitleColumn))
                {
                    CheckBox checkBox = new CheckBox();
                    checkBox.IsChecked = true;

                    if (!String.IsNullOrEmpty(item.SubReportName))
                    {
                        String subReportTitle;
                        this._subReportsTitles.TryGetValue(item.SubReportName, out subReportTitle);

                        //alterado de forma a utilizar o titulo de subreport como resourceKey
                        subReportTitle = (string)ResourceProviderManager.GetResourceProvider().TryGetResource(subReportTitle);
                        if (String.IsNullOrEmpty(subReportTitle))
                            checkBox.Content = item.TitleColumn;
                        else
                            checkBox.Content = item.TitleColumn + " - " + subReportTitle;
                    }
                    else
                        checkBox.Content = item.TitleColumn;

                    checkBox.Name = item.PropertyName;
                    this._container.Children.Add(checkBox);
                }
                i++;
            }
        }

        void header_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        #endregion
    }
}
